package com.zxq.exchange.observer;


import com.zxq.exchange.EFrame;
import com.zxq.exchange.ExchangeDTO;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 通知设备，有消息下发
 */
public class NotifyDeviceRegister {

    static ConcurrentHashMap<EFrame,NotifyDeviceRegister> notifyDeviceRegisterHashMap = new ConcurrentHashMap<EFrame,NotifyDeviceRegister>();

    /**
     * 获取注册者
     * @return
     */
    public static NotifyDeviceRegister getInstance(EFrame tcpFrame) {
        if(notifyDeviceRegisterHashMap.get(tcpFrame) == null) {
            NotifyDeviceRegister notifyDeviceRegister = new NotifyDeviceRegister();
            notifyDeviceRegisterHashMap.put(tcpFrame,notifyDeviceRegister);
        }

        return notifyDeviceRegisterHashMap.get(tcpFrame);
    }

    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2,8,30L, TimeUnit.SECONDS,new ArrayBlockingQueue<>(10));
    /**
     * 消息注册监听
     */
    List<INotifyDevice> registerCenter = new ArrayList<>();

    /**
     * 注册监听服务
     * @param listen
     */
    public void registerNotify(INotifyDevice listen){
        registerCenter.add(listen);
    }

    /**
     * 消息提醒
     */
    public void notifyMessage(ExchangeDTO exchangeDTO) {
        threadPoolExecutor.execute(() -> {
            registerCenter.forEach(listen -> {
                listen.notifyDevice(exchangeDTO);
            });
        });
   }









}
